class UserController < ApplicationController
  def index
  end
  
  def register
    @title = '会员注册'
    if session[:new_user]
      @user = session[:new_user]
      session[:new_user] = nil
    else
      @user = User.new
    end
  end

  def register_action
    user = User.new(params['user'])
    if user.valid?
      
      # set the status = '1' temporarily
      user.status = '1'

      user.save

      # send the activation email to the user
      unencrypted_password = params['user']['password']
      activate_url = url_for({ :controller => 'user', :action => 'activate',
                          :code => "#{user.activation_code}", :uid => "#{user.id}" })
      Mailer.deliver_registration_mail(user, unencrypted_password, activate_url)
      
      # forward to register completed page
      @new_user = user
      @title = '会员注册成功'
      render_action 'register_completed'
    else
      user.password = ''  # empty the password
      session[:new_user] = user
      redirect_to :controller => 'user', :action => 'register'
    end
  end

  def activate
    @user = User.find(params[:uid])
    if @user and @user.status == 0
      @user.status = 1
      @user.activated_at = Time.now
      @user.save
    end

    @title = '帐号激活'
  end
  
  def login
    @title = '会员登录'
    @action_config.merge!({
        :header_partial => false,
        :left_partial => false
    })
  end

  def login_action
    user = User.authenticate(params[:user][:email], params[:user][:password])
    if user
      # store user's id to session
      session[:user] = user
      #redirect_back_or_default(:controller => '/app')
      #flash[:notice] = "Logged in successfully"
      redirect_to :controller => 'home', :action => 'index'
    else
      # we should identify the failed reasons later
      flash[:notice] = "登录失败！"
      redirect_to :controller => 'user', :action => 'login'
    end
  end

  def myzone
    @title = '我的彩艺'
  end

  def edit
    if session[:user]
      @user = session[:user]
      @title = '修改个人资料'
      @user.password = ''
    else
      flash[:notice] = "Session is expired！"
      redirect_to :controller => 'user', :action => 'login'
    end
  end

  def edit_action
    if session[:user]
      @user = session[:user]
      @title = '修改个人资料'
      @user.password = ''
    else
      flash[:notice] = "Session is expired！"
      redirect_to :controller => 'user', :action => 'login'
    end
  end

  def logout
    if session[:user] != nil
      session[:user] = nil
    end
    
    redirect_to :controller => 'home', :action => 'index'
  end

  def forget_password

  end
end
